const express = require('express')
const app = express()
const superagent = require('superagent') // 发起请求得到请求后的（静态）html模板
const cherrio = require('cheerio') // 对html模板进行解析
const Nightmare = require('nightmare')
const nightmare = Nightmare({
  show: true
})
// const Tesseract = require('tesseract.js') // 图片识别库
const Tesseract = require('node-tesseract') // 图片识别库

let server = app.listen(3000, () => {
  console.log('server is starting...')
})


let getHotNews = res => {
  let hotNews = []
  let $ = cherrio.load(res.text)
  $('div#pane-news .hotnews ul li a').each((index, element) => {
    let news = {
      title: $(element).text(),
      href: $(element).attr('href')
    }
    hotNews.push(news)
  })
  return hotNews
}

// 抓取不需要加载的数据
let url = 'https://cas.ctbiyi.com/cas/login?service=https%3A%2F%2Fworkbench.ctbiyi.com%2F'
let html = ''
/* superagent.get(url).end((err, res) => {
  if (err) {
    console.log('catch error')
  } else {
    html = res.text
  }
}) */

// 抓取需要加载的数据
/* nightmare
  .goto(url)
  .wait('#captcha_img')
  .type('#username', 'yaoxu_zz')
  .type('#password', 'd8rshbzli@')
  .evaluate(() => document.querySelector('#fm1').innerHTML)
  .then(htmlStr => {
    html = htmlStr
  })
  .catch(err => {
    console.log('localNews catch error', err)
  }) */

// Tesseract.recognize('https://cas.ctbiyi.com/cas/api/system/getCaptcha', 'eng', {
//   logger: m => console.log(m)
// }).then(({
//   data: {
//     text
//   }
// }) => {
//   console.log(text)
// })

Tesseract.process('https://cas.ctbiyi.com/cas/api/system/getCaptcha', (err, text) => {
  if (err) {
    console.error(err)
  } else {
    console.log(text)
  }
})

app.get('/', async (req, res, next) => {
  // let html = await nightmare
  //   .goto(url)
  //   .wait('#captcha_img')
  //   .evaluate(() => document.querySelector('#captcha_img').innerHTML)
  //   .end()
  //   .then()
  //   .catch(err => {
  //     console.log('localNews catch error', err)
  //   })
  // res.send(html)
})